<template>
  <el-select v-model="logistics_value" placeholder="物流商" clearable filterable @change="change">
    <el-option v-for="item in logisticsOptions" :key="item.logistics_id" :label="item.logistics_name" :value="item.logistics_id" />
  </el-select>

  <el-select class="selectClass" v-model="channel_value" placeholder="物流渠道" @change="changeChannel">
    <el-option v-for="item in channelOptions" :key="item.channel_id" :label="item.channel_name" :value="item.channel_id" />
  </el-select>
</template>
<script setup>
import useCommonStore from "@/store/modules/common";
import { getLogisticsChannel } from '@/api/public'

const commonStore = useCommonStore();
const logisticsOptions = computed(() => {
  if (!commonStore.logisticsOptions) {
    commonStore.getLogisticsList()
  }
  return commonStore.logisticsOptions
});
const props = defineProps({
  modelValue: [String, Number, Array],
  channel: [String, Number],
  logistics: [String, Number],
  placeholder: {
    type: String,
    default: '请选择',
  },
  
});

const channelOptions = ref([])

const value = ref()
watch(() => props.modelValue, (val) => {
  value.value = val
})

const logistics_value = computed({
  get: () => {
    const logistics = props.logistics
    if (!logistics) reset()
    else changeLogistics(logistics)
    return logistics
  },
  set: (val) => {
    emit('update:logistics', val)
  }
});
const channel_value = computed({
  get: () => props.channel,
  set: (val) => {
    emit('update:channel', val)
  }
});

const emit = defineEmits(['update:logistics','update:channel','changeLogistics'])
const change = (val) => {
  const item = logisticsOptions.value.find(i => i.logistics_id == val)
  changeLogistics(val)
  nextTick(() => {
    channelOptions.value = []
    emit('update:channel', '')
    emit('update:logistics', val)
    emit('changeLogistics', item?.logistics_name || '')
  })
}

const changeLogistics = async(val) => {
  try{
    const res = await getLogisticsChannel(val)
    channelOptions.value = res.data
  }catch(e){
    throw Error(e)
  }
}

const changeChannel = (val) => {
  const item = channelOptions.value.find(i => i.logistics_id == val)
  emit('update:channel', val)
  emit('changeChannel', item?.channel_name || '')
}

const reset = () => {
  channelOptions.value = []
}

</script>